<?php
// Podcast - lib.php, 09/02/2008
require_once("$CFG->dirroot/lib/tablelib.php");
require_once("myLib.php");
/**
 * Fonctions relative à Moodle
 */

// Ajouter une instance 
function podcast_add_instance($podcast) {
    
    $podcast->timemodified = time();
		return insert_record("podcast", $podcast);	
}

// Mettre é jour une instance
function podcast_update_instance($podcast) {

    $podcast->timemodified = time();
    $podcast->id = $podcast->instance;

    return update_record("podcast", $podcast);
}

// Supprimer une instance
function podcast_delete_instance($id) {

	 global $CFG;

    if (! $podcast = get_record("podcast", "id", "$id")) {
        return false;
    }

    $result = true;

    if (! delete_records("podcast", "id", "$podcast->id")) {
		$result = false;
    } else {
		// Supprossion SQL
		delete_records("podcast_structure", "id_podcast", "$podcast->id");
		
		// Suppression physique si on est en mode UPLOAD*
		if(strcmp($CFG->podcast_mode ,'LINKING_ONLY')){
			unlink($CFG->dirroot."/mod/podcast/publication/".$podcast->course."/rss".$podcast->id.".xml");
			effacer($CFG->dirroot."/mod/podcast/media/".$podcast->course."/".$podcast->id);
		}
	}

    return $result;
}

// Fonction inutilisée
function podcast_user_outline($course, $user, $mod, $podcast) {
	$return = NULL;
    return $return;
}

// Fonction inutilisée
function podcast_user_complete($course, $user, $mod, $podcast) {
    return true;
}

// // Fonction inutilisée
function podcast_print_recent_activity($course, $isteacher, $timestart) {
    return false;
}

// Fonction executée par le cron Moodle
function podcast_cron() {
    global $CFG;
	
	// Nettoyage des fichiers orphelins
	if ($podcasts = get_records("podcast")) {

		if(!strcmp($CFG->podcast_mode ,'UPLOAD_ONLY')){
			foreach($podcasts as $podcast) {
				if(!$course = get_record("course","id",$podcast->course)) {
					delete_records("podcast", "id", $ipodcast->id);
					delete_records("podcast_structure", "id_podcast", $podcast->id);
					effacer($CFG->dirroot."/mod/podcast/media/".$podcast->course);
					effacer($CFG->dirroot."/mod/podcast/publication/".$podcast->course);
				}    
			}
		}
	}

    $debug = null;
    //Génération d'un nouvelle signature si le module est en mode PCP
    if(!strcmp($CFG->podcast_mode ,'PCP')){
        $cle=md5(uniqid(rand(), true));
        //On va stocker cette clé dans un fichier sur le serveur moodle comme sur le serveur de PcP
        $fichierLocal = fopen($CFG->dataroot.'/secretpartage_tmp', 'w');
        if(!$fichierLocal)
            $debug = "Erreur à la creation du fichier -> Permission \n";
        if(!fputs($fichierLocal,$cle))
            $debug .= "Erreur à l'ecriture, forcément. \n";
        fclose($fichierLocal);
        //On upload le fichier sur le serveur PcP
        if(!strrchr($CFG->podcast_path2tmpfiles, "/") || !strrchr($CFG->podcast_path2tmpfiles, '\\'))
            $path = $CFG->podcast_path2tmpfiles."/";
        $commandUP = "scp -i ".$CFG->podcast_path2rsakey." ".$CFG->dataroot."/secretpartage_tmp ".$CFG->podcast_username."@".$CFG->podcast_path2pcp.":".$path."secretpartage";
        $response =  exec($commandUP, $output, $return);
        //Si le transfert est un succes, on remplace l'ancienne clé par la nouvelle.
        if($return == 0){
            if(!unlink($CFG->dataroot.'/secretpartage'))
                $debug .= "Erreur unlink secretpartage\n";
            if(!rename($CFG->dataroot.'/secretpartage_tmp', $CFG->dataroot.'/secretpartage'))
                $debug .= "Erreur rename\n";
        }else{
            $debug .= "\nValeur de la signature : ".$cle."\n";
            $debug .= "CMDUP : ".$commandUP."\n";
            $debug .= "Valeur de retour de la commande ssh :".$return.":\n";
            //On détruit le fichier temporaire.
            if(!unlink($CFG->dataroot.'/secretpartage_tmp'))
                $debug .= "Erreur unlink secretpartage_tmp\n";
        }
    }
    if($debug != null){
        echo $debug;
        return false;
    }else{
        return true;
    }
}

// Fonction inutilisée
function podcast_grades($podcastid) {
   return NULL;
}

// Fonction inutilisée
function podcast_get_participants($podcastid) {
    return false;
}

// Fonction inutilisée
function podcast_scale_used ($podcastid,$scaleid) {
    return false;
}

/******************************************************************************/
/**
 * Fonctions relative à l'activité Podcast
 */
 
 
//Permet de gérer les items uppés
function podcast_manage_item($podcast, $id) {
	$browse = get_string('browse', 'podcast');
	
	if(!$pd = get_record("modules", "name", "podcast")){
		error("Database connectivity error");
	}

   if (!$cm = get_record("course_modules", "instance", $podcast->id, "module", $pd->id)) {
		error("Course Module ID was incorrect");
	}
	
	$usehtmleditor = can_use_html_editor();
	
	echo '<center style="font-size:14px;">';
 
	global $USER, $CFG;
	$has_media = false;
	if ($pcs = get_records_select($CFG->podcast_feed, "owner = '$USER->username' AND alive = 1", "id DESC")) {
		$has_media = true;
		echo '<p><b>'.utf8_encode(stripslashes(get_string("listingFichier", "podcast"))).':</b></p>';
	}else{
		$has_media = false;
		echo '<p><b>'.utf8_encode(stripslashes(get_string("noListingFichier", "podcast"))).'.</b></p>';
	}
	
	//Utilisation de la librairie pour faire des tableaux de moodle : tablelib.php
	$colonnes = array('date', 'title', 'desc', 'link', 'ajouter', 'detruire');
	//Header du tableau
	$header = array('Date', get_string("name", "podcast"),get_string("desc", "podcast"),get_string("lien", "podcast"), get_string("ajouter", "podcast"), get_string("suppr", "podcast"));
	$table = new flexible_table('Listing des items');
	$table->define_columns($colonnes);
	$table->define_headers($header);
	$table->set_attribute('cellpadding', '5');
	$table->set_attribute('id','document_list');
	$table->set_attribute('class','generaltable generalbox');
	$table->column_style_all("vertical-align", "middle");
    $table->column_style( 'date', "width", '10%');
	$table->column_style( 'title', "width", '10%');
	$table->column_style( 'desc', "width", '30px');
	$table->column_style( 'link', "width", '20px');
	$table->column_style( 'ajouter', "width", '5%');
	$table->column_style( 'detruire', "width", '5%');
	$table->setup();
	

	if ($has_media) {
		foreach($pcs as $item) {
         $dateItem = date( "d/m/Y", strtotime( $item->date ) );
		 $data = array($dateItem, str_replace("_", " ",str_replace("_", " ", stripslashes($item->title))), str_replace("_", " ",stripslashes($item->desc)), "<a href=\"$item->link\">$item->link</a>", "<center><a href='view.php?id=$cm->id&tab=manage&ajouter=$item->id'><img src=\"./icon_podcast/PodcastAdd48.png\"/></a></center>", "<center><a href='view.php?id=$cm->id&tab=manage&delete=$item->id'><img src=\"./icon_delete/delete.png\"/></a></center>");
		 $table->add_data($data);
		}
	}
	$table->print_html();
		

	echo '</center>';	

}

function podcast_add_item($podcast, $id) {
	global $CFG;

	$browse = get_string('browse', 'podcast');

   if (!$cm = get_record("course_modules", "id", $id)) {
		error("Course Module ID was incorrect");
	}
	
	$usehtmleditor = can_use_html_editor();

	if(!strcmp($CFG->podcast_mode ,'UPLOAD_ONLY')){
		?>
		
		<form name="form" method="post" id="form" action="view.php">
			<input type="hidden" name="id"          value="<?php p($id) ?>" />
			<input type="hidden" name="id_item"     value="" />
			<input type="hidden" name="id_podcast"  value="<?php p($podcast->id) ?>" />
			<input type="hidden" name="tab"         value="view" />
			<input type="hidden" name="action"      value="create" />
			<input type="hidden" name="pubdate"     value="<?php echo podcast_date_format(); ?>" />
			<input type="hidden" name="date_html"      value="<?php echo podcast_date_format_html($podcast->lang); ?>" />
			<input type="hidden" name="duration"    value="00:00:00" />
			<input type="hidden" name="length"      value="000000" />
			<center>
			 <table cellpadding="5">	
				<?php  
					global $USER, $CFG;
				
					echo '	
							<tr>
								<td align="right" valign="top"><b>'.get_string("title", "podcast").':</b></td>
								<td align="left"><input type="text" name="title" size="30" value="" /></td>
							</tr>
							<tr>
							  <td align="right" valign="top"><b>'.get_string('desc', 'podcast').':</b></td>
							  <td align="left">';
							  print_textarea($usehtmleditor, 15, 40, 400, 300, "intro","");
							  echo'</td>
							</tr>
							<tr>
							  <td align="right" valign="top"><b>'.get_string('link', 'podcast').' :</b></td>
							  <td align="left">
								<input type="text" name="lien" size="30" value="" alt="lien" />';
							   
								 button_to_popup_window ("/mod/podcast/files/index.php?id=$podcast->course&amp;pod=$podcast->id&amp;choose=form".$item->id.".lien", "coursefiles", $browse, 500, 790, $browse);
							   
					echo'	  </td>
							</tr>';
			
				?>
				
			  </table>
			  <input type="submit" value="<?php print_string('add_item', "podcast") ?>"/>
			</center>	
		</form>
		
		<?php
	}else{
		//error("This feature is only accessible if your administrator has set it");
	}

}

function helpLink($podcast, $id){
echo 'aideLink';
}

function helpUp($podcast, $id){
echo 'aide Up';
}

function helpPcp($podcast, $id){
echo 'aide PCP';
}
// Editer un article
function podcast_edit_item($podcast, $id) {
	global $CFG;
	global $USER;
	
   if (!$cm = get_record("course_modules", "id", $id)) {
		error("Course Module ID was incorrect");
	}	
	
	get_item_podcast($podcast,$id);
}

// Afficher la liste des articles à editer
function get_item_podcast($podcast,$id) {
	global $CFG;
	
	if(!strcmp($CFG->podcast_mode ,'UPLOAD_ONLY')){//Dans ce cas on permet d'editer les métas de l'artcile correspondant.
	
		$browse = get_string('browse', 'podcast');
		
		$usehtmleditor = can_use_html_editor();
		
		if ($items = get_records("podcast_structure", "id_podcast", $podcast->id)) {
			foreach($items as $item) { ?>
				<form name="form<?php echo $item->id;?>" method="post" action="view.php">
				<center>
				<table cellpadding="5">		
				<tr>
					<td align="right" valign="top"><b><?php print_string("title", "podcast") ?></b></td>
					<td align="left"><input type="text" name="title" size="30" value="<?php p(stripslashes($item->title)) ?>" />
					<a href="?id=<?php echo $id; ?>&amp;tab=edit&amp;action=delete&amp;id_item=<?php echo $item->id; ?>" style="color:red;font-size:0.8em;font-weight:bold;">
						<?php print_string('delete', "podcast") ?>
					</a></td>
				</tr>
				<tr>
				  <td align="right" valign="top"><b><?php print_string('desc', 'podcast') ?> :</b></td>
				  <td align="left">
					<?php print_textarea($usehtmleditor, 7, 50, 450, 200, "intro", stripslashes($item->intro)); ?></td>
				</tr>
				<tr>
				  <td align="right" valign="top"><b><?php print_string('file', 'podcast') ?> :</b></td>
				  <td align="left">
					<?php 
					
					$itemlink = $item->lien;
					
					echo "<input type=\"text\" name=\"lien\" size=\"30\" value=\"$itemlink\" alt=\"lien\" />";
					button_to_popup_window ("/mod/podcast/files/index.php?id=$podcast->course&amp;pod=$podcast->id&amp;choose=form".$item->id.".lien", "coursefiles", $browse, 500, 790, $browse);
				?>
				</td>
				</tr>
				</table>
				<input type="hidden" name="id"          value="<?php p($id) ?>" />
				<input type="hidden" name="id_item"          value="<?php p($item->id) ?>" />
				<input type="hidden" name="id_podcast"  value="<?php p($item->id_podcast) ?>" />
				<input type="hidden" name="tab"         value="edit" />
				<input type="hidden" name="action"         value="update" />
				<input type="hidden" name="pubdate"      value="<?php echo podcast_date_format(); ?>" />
				<input type="hidden" name="date_html"      value="<?php echo podcast_date_format_html($podcast->lang); ?>" />
				<input type="hidden" name="duration"      value="<?php p($item->duration) ?>" />
				<input type="hidden" name="length"      value="<?php p($item->length) ?>" />
				<input type="submit" value="<?php print_string('save', "podcast") ?>" />
				</center>
				</form>
				<hr /> <?php
			}
		}
	}else{
		error("This feature is not accessible in this mode.");
	}				
}


// Créer le fichier XML
function make_xml($podcast, $item, $ipod)
	{
	global $CFG;
	require_once($CFG->libdir.'/filelib.php');

	unset($r);
		
		$path = $CFG->wwwroot."/mod/podcast/publication/".$podcast->course."/";
		$file = $path."rss".$podcast->id.".xml";
	
		if(!$ipod){
			$r ='<?xml version="1.0" encoding="UTF-8"?>
				<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" xml:lang=\'fr\'>
		
				<channel>
					<itunes:category text="Education"></itunes:category>
					<atom:link href="'.$file.'" rel="self" type="application/rss+xml" />
					<itunes:explicit>no</itunes:explicit>
					<title>'.str_replace("_", " ", stripslashes($podcast->name)).'</title>
					<description>'.str_replace("_", " ", stripslashes($podcast->intro)).'</description>
					<link>'.$podcast->image_url.'</link>
					<generator>Arche Nancy U</generator>
					<itunes:owner>
						<itunes:name>'.stripslashes($podcast->author).'</itunes:name>
						<itunes:email>'.$podcast->owner_email.'</itunes:email>
					</itunes:owner>
					<itunes:image href="'.$podcast->image_img.'"></itunes:image>';
					
			if((!strcmp($CFG->podcast_mode ,'LINKING_ONLY')) || (!strcmp($CFG->podcast_mode ,'PCP'))){

				foreach($item as $structure) {
					$r .='
					<item>
						<title>'.str_replace("_", " ", $structure->title).'</title>
						<guid>'.$structure->lien.'&amp;id='.$structure->id.'</guid>
						<description>'.str_replace("_", " ", $structure->intro).'</description>
						<link>'.$structure->lien.'</link>
						<pubDate>'.$structure->date_html.'</pubDate>
						<enclosure url="'.$structure->lien.'" length="'.$structure->length.'" type="'.mimeinfo("type",$structure->lien).'" />
						<itunes:explicit>no</itunes:explicit>
						<itunes:duration>'.$structure->length.'</itunes:duration>
					</item>	
				
					';
				}
			}elseif(!strcmp($CFG->podcast_mode ,'UPLOAD_ONLY')){
				foreach($item as $structure) {
	
					$r .='
					<item>
						<title>'.$structure->title.'</title>
						<guid>'.$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$structure->lien.'</guid>
						<description>'.$structure->intro.'</description>
						<link>'.$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$structure->lien.'</link>
						<pubDate>'.$structure->date_html.'</pubDate>
						<enclosure url="'.$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$structure->lien.'" length="'.$structure->length.'" type="'.mimeinfo("type",$structure->lien).'" />
						<itunes:explicit>no</itunes:explicit>
						<itunes:duration>'.$structure->length.'</itunes:duration>
					</item>	
				
					';
				}
			}
		}elseif($ipod && (!strcmp($CFG->podcast_mode ,'LINKING_ONLY') || (!strcmp($CFG->podcast_mode ,'PCP')))){
			$r ='<?xml version="1.0" encoding="UTF-8"?>
				<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" xml:lang=\'fr\'>
		
				<channel>
					<itunes:category text="Education"></itunes:category>
					<atom:link href="'.$file.'" rel="self" type="application/rss+xml" />
					<itunes:explicit>no</itunes:explicit>
					<title>'.str_replace("_", " ", $podcast->name).' '.get_string('ipoddecl', 'podcast').'</title>
					<description>'.str_replace("_", " ", $podcast->intro).'</description>
					<link>'.$podcast->image_url.'</link>
					<generator>Arche Nancy U</generator>
					<itunes:owner>
						<itunes:name>'.$podcast->author.'</itunes:name>
						<itunes:email>'.$podcast->owner_email.'</itunes:email>
					</itunes:owner>
					<itunes:image href="'.$podcast->image_img.'"></itunes:image>';
					
			foreach($item as $structure) {
				
				$fichier = explode(".", $structure->lien);
				$fichier[sizeof($fichier)-2] .= '-ipod';
				$lienIpod = implode(".", $fichier);

				$r .='
				<item>
					<title>'.str_replace("_", " ", $structure->title).'</title>
					<guid>'.$structure->lien.'&amp;id='.$structure->id.'</guid>
					<description>'.str_replace("_", " ", $structure->intro).'</description>
					<link>'.$podcast->image_url.'</link>
					<pubDate>'.$structure->date_html.'</pubDate>
					<enclosure url="'.$lienIpod.'" length="'.$structure->length.'" type="'.mimeinfo("type",$lienIpod).'" />
					<itunes:explicit>no</itunes:explicit>
					<itunes:duration>'.$structure->length.'</itunes:duration>
				</item>	
			
				';
			}
		}
       			
	$r .= '</channel>
	</rss>';
	
	return ($r);
	}
	
//Fonction qui cleanun podcast pour le flux XML
function clean_podcast($podcast, $item){
	cleanText(&$podcast->name);
		cleanText(&$podcast->title);
		cleanText(&$podcast->intro);
		cleanText(&$podcast->author);
		cleanText(&$podcast->owner_email);
		
		foreach($item as $structure) {
			cleanText(&$structure->title);
			cleanText(&$structure->intro);
			cleanText(&$structure->lien);
		}
}

//Fonction qui remplace les caractéres invalidant le XML : & , <
function cleanText($text){
 	$text = str_replace("&","&amp;",$text);
    $text = str_replace("<","&lt;",$text);
	$text = stripslashes($text);
}
	
	
// Afficher un fichier multimédia selon le type MIME
function get_media_html($url) {

    global $CFG, $THEME;
	require_once('../../lib/filelib.php');
	
	echo mimeinfo("",$url);
	
			
	//Suppression du test de mimtype parce que mimeinfo de filelib.php ne connait pas l'extension m4v ...		
			
	if(mimeinfo("type",$url) == "audio/mpeg" || mimeinfo("type",$url) == "audio/mp3"){
		$h = 20;
		$l = 250;
	}else{
		$h = $CFG->podcast_height;
		$l = $CFG->podcast_width;
	}
	
	$html = "<div id='preview'>Veuillez activer javascript pour utiliser le lecteur flash</div>";

	$html .= "<script type='text/javascript'>";
	$html .= "var s1 = new SWFObject('./jwplayer/player.swf','player','".$l."','".$h."','9');";
	$html .= "s1.addParam('allowfullscreen','true');";
	$html .= "s1.addParam('allowscriptaccess','always');";
	$html .= "s1.addParam('flashvars','file=".$url."');";
	$html .= "s1.setAttribute('style', 'margin: 0px auto 10px; display: block;');";
	$html .= "s1.write('preview');";
	$html .= "</script>";


return $html;
	
	
}

	

// Récuperer une date au format XML 2.0
function podcast_date_format() {	
	return date('D, d M Y H:i:s O');
}


// Récupérer une date pour l'affichage html
function podcast_date_format_html($lang) {	
	
	$jour =  date('D'); 
	$mois =  date('M'); 
	
	switch($jour) { 
		case 'Mon': $jour = 'Lundi'; break; 
		case 'Tue': $jour = 'Mardi'; break; 
		case 'Wed': $jour = 'Mercredi'; break; 
		case 'Thu': $jour = 'Jeudi'; break; 
		case 'Fri': $jour = 'Vendredi'; break; 
		case 'Sat': $jour = 'Samedi'; break; 
		case 'Sun': $jour = 'Dimanche'; break; 
		default: $jour =''; break; 
	} 
	switch($mois) { 
		case 'Jan': $mois = 'Janvier'; break; 
		case 'Feb': $mois = utf8_encode('Février'); break;
		case 'Mar': $mois = 'Mars'; break; 
		case 'Apr': $mois = 'Avril'; break; 
		case 'May': $mois = 'Mai'; break; 
		case 'Jun': $mois = 'Juin'; break; 
		case 'Jul': $mois = 'Juillet'; break; 
		case 'Aug': $mois = utf8_encode('Aoét'); break;
		case 'Sep': $mois = 'Septembre'; break; 
		case 'Oct': $mois = 'Octobre'; break; 
		case 'Nov': $mois = 'Novembre'; break; 
		case 'Dec': $mois = 'Decembre'; break; 
		default: $mois =''; break; 
	} 
	
	// Date franéaise
	if (strtolower($lang) == "fr")
		return $jour.' '.date('d')." ".$mois." ".date('Y').' &agrave; '.date('H:i:s');
	else
		return date('D, d M Y H:i:s');
}


// Afficher le Podcast au format hml dans Moodle + Proposer La suppression d'article si on est en mode LINKING et qu'on est admin du cours.
function get_podcast($podcast, $id) {
global $COURSE;

	global $CFG;
		
	// Podcast Reader 
	echo '<div align="center" style="font-size:14px;">';
		// Title
		echo "<h2 align='center'><img src='icon.gif' alt='Podcast' /> ".stripslashes($podcast->name)."</h2>";	
		// General
		echo "<div style='width:270px;float:left;margin-top:100px;'>";
        if($CFG->podcast_image){
            echo "<p style='text-align:center;' ><a href='$podcast->image_url'><img src='$podcast->image_img' alt='".stripslashes($podcast->name)."' /></a></p>";
		}// Description
		echo "<p style='text-align:justify;'>".html_entity_decode($podcast->intro)."</p>";//On fait ca a cause du travail de clean_text fait au moment de la construction du xml
		
	if (file_exists($CFG->dirroot."/mod/podcast/publication/".$podcast->course."/rss".$podcast->id.".xml")) {
		// RSS Icon
		echo '<div style="border-top: 1px solid black;border-bottom: 1px solid black;">';
		echo '<p style="font-weight:bold; font-variant:small-caps;">';
		echo get_string("subscribe", "podcast");
		echo '</p>';
		echo '
			<table>
				<tr>
					<td><a href="'.$CFG->wwwroot.'/mod/podcast/publication/'.$podcast->course.'/rss'.$podcast->id.'.xml"><img src="'.$CFG->wwwroot.'/mod/podcast/icon_flux/Feed.png" width="48" height="48" alt="Raw Feed" /></a></td>';
					
		if($CFG->podcast_fluxipod){
			echo '<td><a href="'.str_replace("http://","itpc://",$CFG->wwwroot).'/mod/podcast/publication/'.$podcast->course.'/rss'.$podcast->id.'-ipod.xml">';
			echo '<img src="'.$CFG->wwwroot.'/mod/podcast/icon_ipod/ipod.png" alt="Ipod" /></a></td>';
		}
				echo '</tr>
			</table>';
			
		echo '</div>';
	}
		// Informations

        if(strcmp($podcast->category, '')){
            echo "<p style='text-align:left;font-size:0.8em;'>" . get_string("category", "podcast") . " : ".stripslashes($podcast->category)."<br />";
        }
		echo get_string('createdby', "podcast")." ".stripslashes($podcast->author)." (".$podcast->owner_email.")</p>";
			
	echo "</div>";
	
	// Items
	echo "<div style='margin-left:300px;margin-top:50px;text-align:left;'>";
		
	if ($podcast_item = get_records("podcast_structure", "id_podcast", $podcast->id, "id DESC")) {
	
		require_once('../../lib/filelib.php');
		
		//Ici on construit une table pour lister nos éléments.
		//Utilisation de la librairie pour faire des tableaux de moodle : tablelib.php
		$table = new flexible_table('Listing des items');
		if(is_allowed('mod/podcast:edit', $podcast->course, $id)){
			$colonnes = array('date', 'title', 'desc', 'link', 'play', 'remove');
			$header = array('Date', get_string("name", "podcast"),get_string("desc", "podcast"),get_string("lien", "podcast"), get_string("lire", "podcast"), get_string("enlever", "podcast"));
			$table->define_columns($colonnes);
			$table->column_style( 'remove', "width", '5%');
		}else{
			$colonnes = array('date', 'title', 'desc', 'link', 'play');
			$header = array('Date', get_string("name", "podcast"),get_string("desc", "podcast"),get_string("lien", "podcast"), get_string("lire", "podcast"));
			$table->define_columns($colonnes);	
		}
		$table->define_headers($header);
		$table->set_attribute('cellpadding', '5');
		$table->set_attribute('width', '100%');
		$table->set_attribute('id','document_list');
		$table->set_attribute('class','generaltable generalbox');
		$table->column_style_all("vertical-align", "middle");
		$table->column_style( 'date', "width", '6%');
		$table->column_style( 'title', "width", '10%');
		$table->column_style( 'desc', "width", '30px');
		$table->column_style( 'link', "width", '20px');
		$table->column_style( 'play', "width", '5%');
		
		//$table->column_style_all("width", '48px');
		
		//$table->pagesize(2, 10);
		//$table->column_style['cf1']['width'] = '10px';
		$table->setup();
	
		foreach($podcast_item as $item) {
		
			if($CFG->podcast_fluxipod){
				$fichier = explode(".", $item->lien);
				$fichier[sizeof($fichier)-2] .= '-ipod';
				$lienIpod = implode(".", $fichier);

				$lien = "<a href=\"$item->lien\">$item->lien</a><br/><a href=\"$lienIpod\">$lienIpod</a>";
			}else{
				$lien = "<a href=\"$item->lien\">$item->lien</a>";
			}
			
			if(mimeinfo("type",$item->lien) == "audio/mpeg" || mimeinfo("type",$item->lien) == "audio/mp3"){
				$h = 20;
				$l = 270;
			}else{
				$h = $CFG->podcast_height+20;
				$l = $CFG->podcast_width+20;
			}
		
			//Je n'utilise pas de get_string ici parce que cela a pour effet d'ouvrir ma page comme un page normale et non comme une popup -_- voodoo code -_-
			if((!strcmp($CFG->podcast_mode ,'LINKING_ONLY')) || (!strcmp($CFG->podcast_mode ,'PCP'))){
					
					//Petite manipulation é faire parce qu'on stocke les dates sous forme de string dans le module de base...
					$dateItem = date( "d/m/Y", strtotime( $item->date_html ) );

                if(is_allowed('mod/podcast:edit', $podcast->course, $id)){

                    $data = array($dateItem, str_replace("_", " ", stripslashes($item->title)), str_replace("_", " ",stripslashes($item->intro)), $lien, "<center>".link_to_popup_window('/mod/podcast/play.php?id='.$item->id , "Lecture de ".str_replace("_", " ", stripslashes($item->title)) , "<img src='./icon_podcast/PodcastPlay48.png'/>", $h, $l, "Lecture de ".str_replace("_", " ", stripslashes($item->title)), "", true)."</center>", "<center><a href='view.php?id=$id&tab=view&delete=$item->id'><img src=\"./icon_podcast/PodcastDelete48.png\"/></a></center>");

				}else{

                    $data = array($dateItem, str_replace("_", " ",stripslashes($item->title)), str_replace("_", " ",stripslashes($item->intro)), $lien, "<center>".link_to_popup_window('/mod/podcast/play.php?id='.$item->id , "Lecture de ".str_replace("_", " ", stripslashes($item->title)) , "<img src='./icon_podcast/PodcastPlay48.png'/>", $h, $l, "Lecture de ".str_replace("_", " ", stripslashes($item->title)), "", true)."</center>");

                }
				
			}else{
	
				if(is_allowed('mod/podcast:edit', $podcast->course, $id)){
				$play =  $CFG->wwwroot."/mod/podcast/play.php?url=".$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$item->lien;
				
					 $data = array($dateItem, str_replace("_", " ",stripslashes($item->title)), stripslashes($item->intro), "<a href='".$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$item->lien."'>".$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$item->lien."</a>", "<center>".link_to_popup_window($play , "Lecture de ".$item->lien , "<img src='./icon_podcast/PodcastPlay48.png'/>", $h, $l, "Lecture de ".str_replace("_", " ", stripslashes($item->title)), "", true)."</center>", "<center><a href='view.php?id=$id&tab=view&delete=$item->id'><img src=\"./icon_podcast/PodcastDelete48.png\"/></a></center>");
				}else{
					 $data = array($dateItem, str_replace("_", " ",stripslashes($item->title), stripslashes($item->intro)), "<a href='".$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$item->lien."'>".$CFG->wwwroot."/mod/podcast/media/".$podcast->course."/".$podcast->id."/".$item->lien."</a>", "<center>".link_to_popup_window($play , "<img src='./icon_podcast/PodcastPlay48.png'/>", $h, $l, "Lecture de ".str_replace("_", " ", stripslashes($item->title)), "", true)."</center>");
				}
			}
		 $table->add_data($data);
		 
		}
		
		$table->print_html();
		
		
	} else {
		echo '<h3 style="font-style:italic;">'.get_string("no_item", "podcast").'</h2>';
	}
	echo "</div>";
	echo "<div style='clear:both;'></div>";
		
	echo "</div>";

}

//Fonction qui retourne le code JS qui permet de récupérer, d'afficher et de soumettre les métadatas.
function metaDataHandler($get, $id){
    global $CFG;
    //Metas Filling
    $codeJS = "function FillMetas(camera, cameraName){
                    if(camera != 0){
                        var backBtnImgWF = YAHOO.util.Dom.get('backImgWF'+camera);
                        backBtnImgWF.setAttribute('src', './icon_load/back-button-up.png');
                        var backBtnImgWFS = YAHOO.util.Dom.get('backImgWFS'+camera);
                        backBtnImgWFS.setAttribute('src', './icon_load/back-button-up.png');
                    }
                    var validBtnImgWF = YAHOO.util.Dom.get('validImgWF'+camera);
                    validBtnImgWF.setAttribute('src', './icon_load/valid-button-up.png');
                    var validBtnImgWFS = YAHOO.util.Dom.get('validImgWFS'+camera);
                    validBtnImgWFS.setAttribute('src', './icon_load/valid-button-up.png');
                    var select = YAHOO.util.Selector.query('.formWFS select', camera, true);
                    var selectedWorkflow = select.options[select.selectedIndex].value;
                    var selectdiv = YAHOO.util.Selector.query('.formWFS', camera, true);
                    YAHOO.util.Dom.setStyle(selectdiv, 'display', 'none');
                    var filldiv = YAHOO.util.Selector.query('.formWF', camera, true);
                    var fillform = YAHOO.util.Selector.query('.formWF form', camera, true);
                    var WF = workflows.getElementsByTagName('workflow');
                    if(fillform.hasChildNodes()){
                        while(YAHOO.util.Dom.getFirstChild(fillform)){
                            fillform.removeChild(YAHOO.util.Dom.getFirstChild(fillform));
                        }
                    }
                    for (var i=0; i<WF.length; i++){
                        if(WF[i].childNodes[3].firstChild.nodeValue == selectedWorkflow){
                            input = document.createElement('input');
                            input.setAttribute('type', 'hidden');
                            input.setAttribute('name', 'uuid');
                            input.setAttribute('value', WF[i].childNodes[3].firstChild.nodeValue);
                            fillform.appendChild(input);
                            input = document.createElement('input');
                            input.setAttribute('type', 'hidden');
                            input.setAttribute('name', 'camera');
                            input.setAttribute('value', cameraName);
                            fillform.appendChild(input);
                            UR = WF[i].getElementsByTagName('require');
                            var table = document.createElement('table');
                            for (var j=0; j<UR.length; j++){
                                var label = document.createElement('label');
                                var input = document.createElement('input');
                                label.appendChild(document.createTextNode(UR[j].firstChild.nodeValue+': '));
                                var ligne = document.createElement('tr');
                                var c1 = document.createElement('td');
                                var c2 = document.createElement('td');
                                c1.appendChild(label);
                                input.setAttribute('type', 'text');
                                input.setAttribute('name', UR[j].firstChild.nodeValue);
                                c2.appendChild(input);
                                ligne.appendChild(c1);
                                ligne.appendChild(c2);
                                table.appendChild(ligne);
                            }
                            table.setAttribute('width', '100%');
                            fillform.appendChild(table);
                        }
                    }
                    YAHOO.util.Dom.setStyle(filldiv, 'display', '');
                    return false;
                }";


   $codeJS .= "function submitMetas(camera, cameraName){
                    var filldiv = YAHOO.util.Selector.query('.formWF', camera, true);
                    var fillform = YAHOO.util.Selector.query('.formWF form', camera, true);
                    var cancelbtn = YAHOO.util.Dom.get('cancel'+camera);
                    YAHOO.util.Dom.setStyle(cancelbtn, 'display', 'none');
                    var recordbtn = YAHOO.util.Dom.get('record'+camera);
                    YAHOO.util.Dom.setStyle(recordbtn, 'display', 'none');
                    var barre = YAHOO.util.Dom.get('loadingBar');
                    YAHOO.util.Dom.setStyle(barre, 'display', '');
                    YAHOO.util.Dom.setStyle(filldiv, 'display', 'none');
                    YAHOO.util.Connect.setForm(fillform);
                    var cObj = YAHOO.util.Connect.asyncRequest('post', '".$CFG->wwwroot."/mod/podcast/submeta.php?perform=camera&instid=$id&cam='+cameraName+'&cuuid='+camera, callbackFormulaire);
                    return false;
               }";

    return $codeJS;
}

//Fonction qui permet de gérer le téléchargement d'un podcast.
function upload_item_podcat($podcast, $id){
    global $CFG, $COURSE, $USER;

    global $CFG, $COURSE, $USER;

    if(is_allowed('mod/podcast:edit', $COURSE->id, $id)){
        //On récupère le secret partagé dans le fichier.
        $fichierLocal = fopen($CFG->dataroot.'/secretpartage', 'r');
        $cle = fread ($fichierLocal, filesize ($CFG->dataroot.'/secretpartage'));
        fclose ($fichierLocal);
        //Signature pour partager l'authentification entre les serveurs.
        $transaction_signature = md5($USER->username . $cle);

        //On va faire péter de l'ajax.
        echo require_js(array('yui_yahoo','yui_event', 'yui_connection', 'yui_dom', 'yui_selector', 'yui_element', 'yui_event', 'yui_uploader', 'yui_datasource'));

         //Barre de chargement
        $barre = '<div id="loadingBar" style="position:fixed; right:22px; bottom:0px; display:none; width:200px;"><img src="'.$CFG->wwwroot.'/mod/podcast/icon_load/activity.gif"/></div>';
        echo $barre;
        
        echo '<center style="font-size:14px;">';
            $table = new flexible_table('Telecharger');
            $colonnes = array('upload');
            $header = array(get_string("uploader", "podcast"));
            $table->define_columns($colonnes);
            $table->define_headers($header);
            $table->set_attribute('cellpadding', '5');
            $table->set_attribute('id','uploaderBox');
            $table->set_attribute('class','generaltable generalbox');
            $table->column_style_all("vertical-align", "middle");
            $table->column_style_all("text-align", "center");
            $table->column_style( 'upload', "width", '300px');
            $table->setup();

            $data = Array('<div style="background-color:#DEDEDE; background-image:url(./icon_load/1.png);padding:5px; margin:5;background-position:left top;background-repeat:no-repeat;">
                        <h2>'.get_string("chose", "podcast").'</h2>
                        <div id="upldrcontainer" style="width:100px; height:40px; margin-right:200px; margin-left:200px;"></div>
                        <div id="progressBar" style="width:100px; height:20px; background-color:#CCCCCC; margin-right:200px; margin-left:200px;"></div>
                        <a style="display:none" id="cancelUp" onClick="cancelUploading();">
                            <img id="cancelImgUp" src="./icon_load/cancel-button-up.png" title="'.get_string("cancel", "podcast").'" alt="'.get_string("cancel", "podcast").'"/>
                        </a>
                    </div>
                  
                 <div id="0">
                     <div class="formWF" style="display:none; background-color:#DEDEDE; width:100%; height:100%; background-image:url(./icon_load/3.png); margin:5;background-position:left top;background-repeat:no-repeat;">
                        <h2>'.get_string("fill", "podcast").'</h2>
                        <form id="formWFform">
                        </form>
                        <p>
                           <a id="validWF0" onClick="var validbtnImg = YAHOO.util.Dom.get(\'validImgWF0\');
                                                validbtnImg.setAttribute(\'src\', \'./icon_load/valid-button-down.png\'); Process();">
                                <img id="validImgWF0" src="./icon_load/valid-button-up.png" title="'.get_string("valid", "podcast").'" alt="'.get_string("valid", "podcast").'"/>
                           </a>
                        </p>
                        <p>
                           <a id="backWF0"  onClick="var backbtnImg = YAHOO.util.Dom.get(\'backImgWF0\');
                                                backbtnImg.setAttribute(\'src\', \'./icon_load/back-button-down.png\'); Back();">
                                <img id="backImgWF0" src="./icon_load/back-button-up.png" title="'.get_string("back", "podcast").'" alt="'.get_string("back", "podcast").'"/>
                           </a>
                        </p>
                    </div>
                    <div class="formWFS" style="display:none; background-color:#DEDEDE; width:100%;  height:100%; background-image:url(./icon_load/2.png); margin:5;background-position:left top;background-repeat:no-repeat;">
                        <h2>'.get_string("select", "podcast").'</h2>
                        <form>
                             <select id="formWFSselect"></select>
                        </form>
                        <p>
                           <a id="validWFS0"  onClick="var validbtnImg = YAHOO.util.Dom.get(\'validImgWFS0\');
                                                validbtnImg.setAttribute(\'src\', \'./icon_load/valid-button-down.png\'); FillMetas(\'0\', \'upload\');">
                                <img id="validImgWFS0" src="./icon_load/valid-button-up.png" title="'.get_string("valid", "podcast").'" alt="'.get_string("valid", "podcast").'"/>
                           </a>
                        </p>
                        <p>
                            <a id="cancelWFS0" onClick="var cancelbtnImg = YAHOO.util.Dom.get(\'cancelImgWFS0\');
                                                cancelbtnImg.setAttribute(\'src\', \'./icon_load/cancel-button-down.png\'); CancelUpload();">
                                <img id="cancelImgWFS0" src="./icon_load/cancel-button-up.png" title="'.get_string("cancel", "podcast").'" alt="'.get_string("cancel", "podcast").'"/>
                            </a>
                        </p>
                    </div>
                </div>');


            $table->add_data($data);

            $table->print_html();

        echo '</center>';

        $codeJS = "<script type=\"text/javascript\">var wfuuid; var filename;;";

        $codeJS .= "YAHOO.widget.Uploader.SWFURL = '".$CFG->wwwroot."/lib/yui/uploader/assets/uploader.swf';
                    var uploader = new YAHOO.widget.Uploader('upldrcontainer', './icon_load/db_comit.png');
                    var fileID;
                    uploader.addListener('contentReady', handleContentReady);
                    uploader.addListener('fileSelect',onFileSelect);
                    uploader.addListener('uploadProgress',onUploadProgress);
                    uploader.addListener('uploadCompleteData',onUploadResponse);
                    uploader.addListener('uploadError', onUploadError);     
            ";

        $codeJS .= 'function handleContentReady () {
                        uploader.setAllowLogging(false);
                        uploader.setAllowMultipleFiles(false);
                        var ff = new Array({description:"Videos", extensions:"*.mov;"});
                        uploader.setFileFilters(ff);
                    }';

        $codeJS .= 'function onFileSelect(event) {
                        for (var item in event.fileList) {
                            if(YAHOO.lang.hasOwnProperty(event.fileList, item)) {
                                fileID = event.fileList[item].id;
                            }
                        }
                        uploader.disable();
                        var cancelbtn = YAHOO.util.Dom.get("cancelUp");
                        YAHOO.util.Dom.setStyle(cancelbtn, "display", "");
                        var progressbar = document.getElementById("progressBar");
                        progressbar.innerHTML = "";
                        upload();
                    }';

        $codeJS .= 'function upload() {
                        if (fileID != null) {
                            uploader.upload(fileID, "'.$CFG->podcast_path2uploadscript.'","POST", {signature:"'.$transaction_signature.'", username:"'.$USER->username.'"});
                        }
                    }';

        $codeJS .= 'function onUploadProgress(event) {
                        prog = Math.round(100*(event["bytesLoaded"]/event["bytesTotal"]));
                        progbar = "<div style=\"background-color: #0dee57; height: 20px; width: " + prog + "px\"/>";
                        var progressbar = document.getElementById("progressBar");
                        progressbar.innerHTML = progbar;
                    }';
        
        $codeJS .= 'function cancelUploading(){
                        uploader.cancel();
                        uploader.enable();
                        var cancelbtn = YAHOO.util.Dom.get(\'cancelUp\');
                        YAHOO.util.Dom.setStyle(cancelbtn, \'display\', \'none\');
                        progbar = "<div style=\"background-color:#f9a116; height: 20px; width: 100px;\">'.get_string("cancelled", "podcast").'</div>";
                        var progressbar = document.getElementById("progressBar");
                        progressbar.innerHTML = progbar;
                    }';

        //Choosing workflow
        $codeJS .= 'function onUploadResponse(event) {
                        var xmlobject = (new DOMParser()).parseFromString(event.data, "text/xml");
                        if(xmlobject.getElementsByTagName("success")[0].firstChild.nodeValue != "SUCCESS"){
                            uploader.clearFileList();
                            progbar = "<div style=\"background-color: #f9a116; height: 20px; width: 100px;\">"+xmlobject.getElementsByTagName("reason")[0].firstChild.nodeValue+"</div>";
                            var progressbar = document.getElementById("progressBar");
                            progressbar.innerHTML = progbar;
                        }else{
                            uploader.clearFileList();
                            filename = xmlobject.getElementsByTagName("filename")[0].firstChild.nodeValue;
                            progbar = "<div style=\"background-color: #0dee57; height: 20px; width: 100px;\">'.get_string("uploaded", "podcast").'</div>";
                            var progressbar = document.getElementById("progressBar");
                            progressbar.innerHTML = progbar;
                            getWorkflows();
                        }
                        var cancelbtn = YAHOO.util.Dom.get("cancelUp");
                        YAHOO.util.Dom.setStyle(cancelbtn, "display", "none");
                    }';

       $codeJS .= "var callbackListWF =
                            {
                              success: function(o) {
                                    if(o.responseXML.getElementsByTagName('response')[0].firstChild.nodeValue != 'SUCCESS'){
                                        alert('".get_string("erreurList", "podcast")."');
                                    }else{
                                        var select = YAHOO.util.Dom.get('formWFSselect');
                                        if(select.hasChildNodes()){
                                            while(YAHOO.util.Dom.getFirstChild(select)){
                                                select.removeChild(YAHOO.util.Dom.getFirstChild(select));
                                            }
                                        }
                                        workflows = o.responseXML;
                                        var WFs = o.responseXML.getElementsByTagName('workflow');
                                        for (var i=0; i<WFs.length; i++){
                                            var option = document.createElement('option');
                                            option.setAttribute('value', WFs[i].childNodes[3].firstChild.nodeValue);
                                            option.appendChild(document.createTextNode(WFs[i].childNodes[2].firstChild.nodeValue));
                                            var option = select.appendChild(option);
                                        }
                                        if(i>0){
                                            selectBox = YAHOO.util.Selector.query('.formWFS', 0, true);
                                            YAHOO.util.Dom.setStyle(selectBox, 'display', '');
                                        }
                                        var barre = YAHOO.util.Dom.get('loadingBar');
                                        YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    }
                                },
                              failure: function(o) {
                                    alert('".get_string("erreurList", "podcast")."');
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 15000,
                            }; ";

        $codeJS .= "var callbackCancelUpload =
                            {
                              success: function(o) {
                                    var cancelbtnImg = YAHOO.util.Dom.get('cancelImgWFS0');
                                    cancelbtnImg.setAttribute('src', './icon_load/cancel-button-up.png');
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    selectBox = YAHOO.util.Selector.query('.formWFS', 0, true);
                                    YAHOO.util.Dom.setStyle(selectBox, 'display', 'none');
                                    var progressbar = document.getElementById('progressBar');
                                    progbar = '<div style=\"background-color:#f9a116; height: 20px; width: 100px;\">".get_string("cancelled", "podcast")."</div>';
                                    progressbar.innerHTML = progbar;
                                    uploader.enable();
                                },
                              failure: function(o) {
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 5000,
                            }; ";

        $codeJS .= "var callbackProcess =
                            {
                              success: function(o) {
                                    var validbtnImg = YAHOO.util.Dom.get('validImgWFS0');
                                    validbtnImg.setAttribute('src', './icon_load/valid-button-up.png');
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    progbar = '<div style=\"background-color: #0dee57; height: 20px; width: 100px;\">".get_string("posted", "podcast")."</div>';
                                    var progressbar = document.getElementById('progressBar');
                                    progressbar.innerHTML = progbar;
                                    uploader.enable();
                                },
                              failure: function(o) {
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 5000,
                            }; ";

        $codeJS .= "function onUploadError(event) {
                        alert(event.status);
                    }";

        $codeJS .= "function getWorkflows(){
                        var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/listWorkflows.php?instid=".$id."', callbackListWF);
                        var barre = YAHOO.util.Dom.get('loadingBar');
                        YAHOO.util.Dom.setStyle(barre, 'display', '');
                    }";

        $codeJS .= "function CancelUpload(){
                        var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/cancelUpload.php?instid=".$id."&filename='+filename, callbackCancelUpload);
                        var barre = YAHOO.util.Dom.get('loadingBar');
                        YAHOO.util.Dom.setStyle(barre, 'display', '');
                    }";

        $codeJS .= "function Process(){
                        var validbtnImg = YAHOO.util.Dom.get('validImgWFS0');
                        validbtnImg.setAttribute('src', './icon_load/valid-button-up.png');
                        var filldiv = YAHOO.util.Selector.query('.formWF', 0, true);
                        var fillform = YAHOO.util.Selector.query('.formWF form', 0, true);
                        YAHOO.util.Dom.setStyle(filldiv, 'display', 'none');
                        YAHOO.util.Connect.setForm(fillform);
                        var connectionObject = YAHOO.util.Connect.asyncRequest ('post', '".$CFG->wwwroot."/mod/podcast/submeta.php?instid=".$id."&perform=upload&filename='+filename, callbackProcess);
                        var barre = YAHOO.util.Dom.get('loadingBar');
                        YAHOO.util.Dom.setStyle(barre, 'display', '');
                    }";

        $codeJS.= "function Back(){
                        selectBox = YAHOO.util.Selector.query('.formWFS', 0, true);
                        YAHOO.util.Dom.setStyle(selectBox, 'display', '');
                        fillBox = YAHOO.util.Selector.query('.formWF', 0, true);
                        YAHOO.util.Dom.setStyle(fillBox, 'display', 'none');
                        var backbtnImg = YAHOO.util.Dom.get('backImgWF0');
                        backbtnImg.setAttribute('src', './icon_load/back-button-up.png');
                   }";

        $codeJS .= metaDataHandler('upload', $id);

        $codeJS .= "</script>";

       echo $codeJS;
    }else{
       error("Permission denied");
    }
}

//Fonction qui permet de gérer l'enregistrement d'un podcast.
function record_item_podcat($podcast, $id){
    require_once("PlistParser.inc");
    global $CFG, $COURSE, $USER;

    if(is_allowed('mod/podcast:edit', $COURSE->id, $id)){
        //On va faire péter de l'ajax dérrière.
        echo require_js(array('yui_yahoo','yui_event', 'yui_connection', 'yui_dom', 'yui_selector', 'yui_container'));

        //Barre de chargement
        $barre = '<div id="loadingBar" style="position:fixed; right:22px; bottom:0px; display:none; width:200px;"><img src="'.$CFG->wwwroot.'/mod/podcast/icon_load/activity.gif"/></div>';
        //Boite de feedback
        $FBP = '<div id="feedBackP" style="position:fixed; right:22px; bottom:0px; display:none; background-color: #9ACD32 height:20px; width:200px;"><img style="vertical-align:bottom;" src="'.$CFG->wwwroot.'/mod/podcast/icon_load/ok.png"/><span id="feedBackPText"></span></div>';
        $FBN = '<div id="feedBackN" style="position:fixed; right:22px; bottom:0px; display:none; background-color: #FF4500 height:20px; width:200px;"><img style="vertical-align:bottom;" src="'.$CFG->wwwroot.'/mod/podcast/icon_load/transmit_error.png"/><span id="feedBackNText"></span></div>';
        echo $barre.$FBP.$FBN;

        //On récupère la liste des caméras.
        $command1 = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." pcast --server ".$CFG->podcast_path2pcp." --user ".$CFG->podcast_username." --pass ".$CFG->podcast_password." --listcameras";
        $output =  shell_exec($command1);
        $parser = new plistParser();
        $plist = $parser->parseRAW($output);

        echo '<center style="font-size:14px;">';
            $colonnes = array('cam', 'preview', 'action');
            //Header du tableau
            $header = array(get_string("cam", "podcast"),get_string("preview", "podcast")."&nbsp;",get_string("act", "podcast"));
            $table = new flexible_table('Listing des cameras');
            $table->define_columns($colonnes);
            $table->define_headers($header);
            $table->set_attribute('cellpadding', '5');
            $table->set_attribute('id','camera_list');
            $table->set_attribute('class','generaltable generalbox');
            $table->column_style_all("vertical-align", "middle");
            $table->column_style_all("text-align", "center");
            $table->column_style( 'cam', "width", '100px');
            $table->column_style( 'preview', "width", '400px');
            $table->column_style( 'action', "width", '300px');
            $table->setup();

            foreach($plist["cameras"] as $camera) {
                 $data = array( $camera["name"], '<img id="preview'.$camera["uuid"].'" src="">',
         '<div id="'.$camera["uuid"].'">
            <div id="open'.$camera["uuid"].'" style="display:none;"><a title="'.get_string("lock", "podcast").'" onClick="getCam(\''.$camera["uuid"].'\', \''.$camera["name"].'\');"><img id="lockImg'.$camera["uuid"].'" src="'.$CFG->wwwroot.'/mod/podcast/icon_load/locker-button-up.png"/></a></div>
            <div id="closed'.$camera["uuid"].'" style="display:none;"><img title="Indisponible" src="'.$CFG->wwwroot.'/mod/podcast/icon_load/locker-button-disabled.png"/></div>
            <div class="formWF" style="display:none;">
                <h2>'.get_string("fill", "podcast").'</h2>
                <form id="formWFform">
                </form>
                <p>
                   <a id="validWF'.$camera["uuid"].'" onClick="var validbtnImg = YAHOO.util.Dom.get(\'validImgWF'.$camera["uuid"].'\');
                                        validbtnImg.setAttribute(\'src\', \'./icon_load/valid-button-down.png\'); submitMetas(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="validImgWF'.$camera["uuid"].'" src="./icon_load/valid-button-up.png" title="'.get_string("valid", "podcast").'" alt="'.get_string("valid", "podcast").'"/>
                   </a>
                </p>
                <p>
                   <a id="backWF'.$camera["uuid"].'"  onClick="var backbtnImg = YAHOO.util.Dom.get(\'backImgWF'.$camera["uuid"].'\');
                                        backbtnImg.setAttribute(\'src\', \'./icon_load/back-button-down.png\'); Stop(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="backImgWF'.$camera["uuid"].'" src="./icon_load/back-button-up.png" title="'.get_string("back", "podcast").'" alt="'.get_string("back", "podcast").'"/>
                   </a>
                </p>
            </div>
            <div class="formWFS" style="display:none;">
                <h2>'.get_string("select", "podcast").'</h2>
                <form>
                     <select></select>
                </form>
                <p>
                   <a id="validWFS'.$camera["uuid"].'"  onClick="var validbtnImg = YAHOO.util.Dom.get(\'validImgWFS'.$camera["uuid"].'\');
                                        validbtnImg.setAttribute(\'src\', \'./icon_load/valid-button-down.png\'); FillMetas(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="validImgWFS'.$camera["uuid"].'" src="./icon_load/valid-button-up.png" title="'.get_string("valid", "podcast").'" alt="'.get_string("valid", "podcast").'"/>
                   </a>
                </p>
                <p>
                   <a id="backWFS'.$camera["uuid"].'" onClick="var backbtnImg = YAHOO.util.Dom.get(\'backImgWFS'.$camera["uuid"].'\');
                                        backbtnImg.setAttribute(\'src\', \'./icon_load/back-button-down.png\'); RefreshCams();">
                        <img id="backImgWFS'.$camera["uuid"].'" src="./icon_load/back-button-up.png" title="'.get_string("back", "podcast").'" alt="'.get_string("back", "podcast").'"/>
                   </a>
                </p>
            </div>
            <div id="cmd'.$camera["uuid"].'" style="display:none;">
                <p>
                   <a id="record'.$camera["uuid"].'" onClick="Record(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="recordImg'.$camera["uuid"].'" src="./icon_load/record-button-up.png" title="'.get_string("record", "podcast").'" alt="'.get_string("record", "podcast").'"/>
                   </a>
                </p>
                <p>
                   <a id="stop'.$camera["uuid"].'" style="display:none;" onClick="Stop(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="stopImg'.$camera["uuid"].'" src="./icon_load/stop-button-up.png" title="Stop" alt="Stop"/>
                   </a>
                <p>
                <p>
                   <a id="pause'.$camera["uuid"].'" style="display:none;" onClick="Pause(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="pauseImg'.$camera["uuid"].'" src="./icon_load/pause-button-up.png" title="Pause" alt="Pause"/>
                   </a>
                </p>
                <p>
                   <a id="cancel'.$camera["uuid"].'" style="" onClick="Cancel(\''.$camera["uuid"].'\', \''.$camera["name"].'\');">
                        <img id="cancelImg'.$camera["uuid"].'" src="./icon_load/cancel-button-up.png" title="'.get_string("cancel", "podcast").'" alt="'.get_string("cancel", "podcast").'"/>
                   </a>
                </p>
            </div>
         </div>');

                 $table->add_data($data);
            }

            $table->print_html();
        echo "</center>";

        //Code JS
        $codeJS = "<script type=\"text/javascript\">
                    var workflows = 0;";

       $codeJS .= "var callbackFormulaire =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    if(o.responseXML.getElementsByTagName('Success')[0].firstChild.nodeValue != 'SUCCESS'){
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = ' ".get_string("erreurSubmit","podcast")."';
                                    }else{
                                        o.responseXML.getElementsByTagName('Success')[0].firstChild.nodeValue
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+camera);
                                        pausebtnImg.setAttribute('src', './icon_load/pause-button-up.png');
                                        pausebtn.setAttribute('onClick', 'Pause(\''+camera+'\', \''+cameraName+'\');');
                                        var cmddiv = YAHOO.util.Dom.get('cmd'+camera);
                                        YAHOO.util.Dom.setStyle(cmddiv, 'display', 'none');
                                        var lockbtn = YAHOO.util.Dom.get('open'+camera);
                                        YAHOO.util.Dom.setStyle(lockbtn, 'display', '');
                                        var stopbtn = YAHOO.util.Dom.get('stop'+camera);
                                        YAHOO.util.Dom.setStyle(stopbtn, 'display', 'none');
                                        var recordbtn = YAHOO.util.Dom.get('record'+camera);
                                        YAHOO.util.Dom.setStyle(recordbtn, 'display', '');
                                        YAHOO.util.Dom.setStyle(pausebtn, 'display', 'none');
                                        var cancelbtn = YAHOO.util.Dom.get('cancel'+camera);
                                        YAHOO.util.Dom.setStyle(cancelbtn, 'display', '');
                                        var recordbtnimg = YAHOO.util.Dom.get('recordImg'+camera);
                                        recordbtnimg.setAttribute('src', './icon_load/record-button-up.png');
                                        selectBox = YAHOO.util.Selector.query('.formWFS', camera, true);
                                        YAHOO.util.Dom.setStyle(selectBox, 'display', 'none');
                                        var stopbtimg = YAHOO.util.Dom.get('stopImg'+camera);
                                        stopbtimg.setAttribute('src', './icon_load/stop-button-up.png');
                                        var filldiv = YAHOO.util.Selector.query('.formWF', camera, true);
                                        YAHOO.util.Dom.setStyle(filldiv, 'display', 'none');
                                        var FBP = YAHOO.util.Dom.get('feedBackP');
                                        YAHOO.util.Dom.setStyle(FBP, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackPText');
                                        FBtext.innerHTML = 'Soumission réussie.';
                                    }
                                    var cancelbtnImg = YAHOO.util.Dom.get('cancelImg'+camera);
                                    cancelbtnImg.setAttribute('src', './icon_load/cancel-button-up.png');
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurSubmit", "podcast")."';
                                },
                              timeout: 5000,
                            }; ";

        //Callback : Success / Failure / Timeout
        $codeJS .= "var callbackRecord =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    if(o.responseXML.getElementsByTagName('success')[0].firstChild.nodeValue != 'SUCCESS'){
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurRecord", "podcast")."';
                                        var barre = YAHOO.util.Dom.get('loadingBar');
                                    }else{
                                        var recordbtn = YAHOO.util.Dom.get('record'+camera);
                                        var stopbtn = YAHOO.util.Dom.get('stop'+camera);
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        YAHOO.util.Dom.setStyle(recordbtn, 'display', 'none');
                                        YAHOO.util.Dom.setStyle(stopbtn, 'display', '');
                                        YAHOO.util.Dom.setStyle(pausebtn, 'display', '');
                                        var stopbtimg = YAHOO.util.Dom.get('stopImg'+camera);
                                        stopbtimg.setAttribute('src', './icon_load/stop-button-up.png');
                                        var barre = YAHOO.util.Dom.get('loadingBar');
                                        YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    }
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurRecord", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    var recordbtn = YAHOO.util.Dom.get('record'+camera);
                                    recordbtn.setAttribute('src', './icon_load/record-button-up.png');
                                },
                              timeout: 15000,
                            }; ";

        $codeJS .= "var callbackStop =
                            {
                              success: function(o) {
                                    var cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    var camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    var backBtnImgWF = YAHOO.util.Dom.get('backImgWF'+camera);
                                    backBtnImgWF.setAttribute('src', './icon_load/back-button-up.png');
                                    var backBtnImgWFS = YAHOO.util.Dom.get('backImgWFS'+camera);
                                    backBtnImgWFS.setAttribute('src', './icon_load/back-button-up.png');
                                    var validBtnImgWF = YAHOO.util.Dom.get('validImgWF'+camera);
                                    validBtnImgWF.setAttribute('src', './icon_load/valid-button-up.png');
                                    var validBtnImgWFS = YAHOO.util.Dom.get('validImgWFS'+camera);
                                    validBtnImgWFS.setAttribute('src', './icon_load/valid-button-up.png');
                                    var fill = YAHOO.util.Selector.query('.formWF', camera, true);
                                    YAHOO.util.Dom.setStyle(fill, 'display', 'none');
                                    if(o.responseXML.getElementsByTagName('response')[0].firstChild.nodeValue != 'SUCCESS'){
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurStop", "podcast")."';
                                    }else{
                                        var select = YAHOO.util.Selector.query('.formWFS select', camera, true);
                                        if(select.hasChildNodes()){
                                            while(YAHOO.util.Dom.getFirstChild(select)){
                                                select.removeChild(YAHOO.util.Dom.getFirstChild(select));
                                            }
                                        }
                                        workflows = o.responseXML;
                                        var WFs = o.responseXML.getElementsByTagName('workflow');
                                        for (var i=0; i<WFs.length; i++){
                                            var option = document.createElement('option');
                                            option.setAttribute('value', WFs[i].childNodes[3].firstChild.nodeValue);
                                            option.appendChild(document.createTextNode(WFs[i].childNodes[2].firstChild.nodeValue));
                                            var option = select.appendChild(option);
                                        }
                                        if(i>0){
                                            selectBox = YAHOO.util.Selector.query('.formWFS', camera, true);
                                            YAHOO.util.Dom.setStyle(selectBox, 'display', '');
                                        }
                                        var stopbtn = YAHOO.util.Dom.get('stop'+camera);
                                        YAHOO.util.Dom.setStyle(stopbtn, 'display', 'none');
                                        var recordbtn = YAHOO.util.Dom.get('record'+camera);
                                        YAHOO.util.Dom.setStyle(recordbtn, 'display', 'none');
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        YAHOO.util.Dom.setStyle(pausebtn, 'display', 'none');
                                        var recordbtnimg = YAHOO.util.Dom.get('recordImg'+camera);
                                        recordbtnimg.setAttribute('src', './icon_load/record-button-up.png');
                                        var form = YAHOO.util.Selector.query('.form', camera, true);
                                        YAHOO.util.Dom.setStyle(form, 'display', '');
                                        var stopbtimg = YAHOO.util.Dom.get('stopImg'+camera);
                                        stopbtimg.setAttribute('src', './icon_load/stop-button-up.png');
                                        var barre = YAHOO.util.Dom.get('loadingBar');
                                        YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    }
                                },
                              failure: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurStop", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    var stopbtn = YAHOO.util.Selector.query('.stop img', camera, true);
                                    stopbtn.setAttribute('src', './icon_load/stop-button-up.png');
                                },
                              timeout: 15000,
                            }; ";


        $codeJS .= "var callbackPause =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    if(o.responseXML.getElementsByTagName('success')[0].firstChild.nodeValue != 'SUCCESS'){
                                        camera = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                        cameraName = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurPause", "podcast")."';
                                        var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+camera);
                                        pausebtnImg.setAttribute('src', './icon_load/pause-button-up.png');
                                    }else{
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        pausebtn.setAttribute('onClick', 'Play(\''+camera+'\', \''+cameraName+'\');');
                                    }
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurPause", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 15000,
                            }; ";

        $codeJS .= "var callbackCancel =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    if(o.responseXML.getElementsByTagName('success')[0].firstChild.nodeValue != 'SUCCESS'){
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurCancel", "podcast")."';
                                    }else{
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+camera);
                                        pausebtnImg.setAttribute('src', './icon_load/pause-button-up.png');
                                        pausebtn.setAttribute('onClick', 'Pause(\''+camera+'\', \''+cameraName+'\');');
                                        var cmddiv = YAHOO.util.Dom.get('cmd'+camera);
                                        YAHOO.util.Dom.setStyle(cmddiv, 'display', 'none');
                                        var lockbtn = YAHOO.util.Dom.get('open'+camera);
                                        YAHOO.util.Dom.setStyle(lockbtn, 'display', '');
                                        var stopbtn = YAHOO.util.Dom.get('stop'+camera);
                                        YAHOO.util.Dom.setStyle(stopbtn, 'display', 'none');
                                        var recordbtn = YAHOO.util.Dom.get('record'+camera);
                                        YAHOO.util.Dom.setStyle(recordbtn, 'display', '');
                                        YAHOO.util.Dom.setStyle(pausebtn, 'display', 'none');
                                        var recordbtnimg = YAHOO.util.Dom.get('recordImg'+camera);
                                        recordbtnimg.setAttribute('src', './icon_load/record-button-up.png');
                                        var stopbtimg = YAHOO.util.Dom.get('stopImg'+camera);
                                        stopbtimg.setAttribute('src', './icon_load/stop-button-up.png');
                                        selectBox = YAHOO.util.Selector.query('.formWFS', camera, true);
                                        YAHOO.util.Dom.setStyle(selectBox, 'display', 'none');
                                        var filldiv = YAHOO.util.Selector.query('.formWF', camera, true);
                                        YAHOO.util.Dom.setStyle(filldiv, 'display', 'none');
                                    }
                                    var cancelbtnImg = YAHOO.util.Dom.get('cancelImg'+camera);
                                    cancelbtnImg.setAttribute('src', './icon_load/cancel-button-up.png');
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurCancel", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 15000,
                            }; ";

        $codeJS .= "var callbackResume =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    if(o.responseXML.getElementsByTagName('success')[0].firstChild.nodeValue != 'SUCCESS'){
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurResume", "podcast")."';
                                    }else{
                                        var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+camera);
                                        pausebtnImg.setAttribute('src', './icon_load/pause-button-up.png');
                                        var pausebtn = YAHOO.util.Dom.get('pause'+camera);
                                        pausebtn.setAttribute('onClick', 'Pause(\''+camera+'\', \''+cameraName+'\');');
                                    }
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurResume", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 15000,
                            }; ";

         $codeJS .= "var callbackRefresh =
                            {
                              success: function(o) {
                                    var cameras = o.responseXML.getElementsByTagName('camera');
                                    for (var i=0; i<cameras.length; i++){
                                        var preview = YAHOO.util.Dom.get('preview'+cameras[i].childNodes[1].firstChild.nodeValue);
                                        preview.setAttribute('src', '".$CFG->wwwroot."/file.php/".$COURSE->id."/podcast/'+cameras[i].childNodes[1].firstChild.nodeValue+'.png".floor(time()/600)."');
                                        if(cameras[i].childNodes[6].getAttribute('user') == ".$USER->id."){
                                            var cmddiv = YAHOO.util.Dom.get('cmd'+cameras[i].childNodes[1].firstChild.nodeValue);
                                            YAHOO.util.Dom.setStyle(cmddiv, 'display', '');
                                            var recordbtn = YAHOO.util.Dom.get('record'+cameras[i].childNodes[1].firstChild.nodeValue);
                                            var stopbtn = YAHOO.util.Dom.get('stop'+cameras[i].childNodes[1].firstChild.nodeValue);
                                            var pausebtn = YAHOO.util.Dom.get('pause'+cameras[i].childNodes[1].firstChild.nodeValue);
                                            regExpCap = new RegExp('capturing', 'i');
                                            regExpPause = new RegExp('paused', 'i');
                                            if(regExpCap.test(cameras[i].childNodes[2].firstChild.nodeValue) || regExpPause.test(cameras[i].childNodes[2].firstChild.nodeValue)){
                                                YAHOO.util.Dom.setStyle(stopbtn, 'display', '');
                                                YAHOO.util.Dom.setStyle(pausebtn, 'display', '');
                                                var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                if(regExpPause.test(cameras[i].childNodes[2].firstChild.nodeValue)){
                                                    pausebtnImg.setAttribute('src', './icon_load/pause-button-down.png');
                                                    pausebtn.setAttribute('onClick', 'Play(\''+cameras[i].childNodes[1].firstChild.nodeValue+'\', \''+cameras[i].childNodes[0].firstChild.nodeValue+'\');');
                                                }else{
                                                    pausebtnImg.setAttribute('src', './icon_load/pause-button-up.png');
                                                    pausebtn.setAttribute('onClick', 'Pause(\''+cameras[i].childNodes[1].firstChild.nodeValue+'\', \''+cameras[i].childNodes[0].firstChild.nodeValue+'\');');
                                                }
                                                YAHOO.util.Dom.setStyle(recordbtn, 'display', 'none');
                                            }else{
                                                YAHOO.util.Dom.setStyle(stopbtn, 'display', 'none');
                                                YAHOO.util.Dom.setStyle(recordbtn, 'display', '');
                                                var stopbtimg = YAHOO.util.Dom.get('stopImg'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                stopbtimg.setAttribute('src', './icon_load/stop-button-up.png');
                                                var recordbtnImg = YAHOO.util.Dom.get('recordImg'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                recordbtnImg.setAttribute('src', './icon_load/record-button-up.png');
                                            }
                                        }else{
                                            if((cameras[i].childNodes[6].firstChild.nodeValue == 'LOCKED') && (cameras[i].childNodes[6].firstChild.getAttribute != '".$USER->id."')){
                                                var closedbtn = YAHOO.util.Dom.get('closed'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                YAHOO.util.Dom.setStyle(closedbtn, 'display', '');
                                                var openbtn = YAHOO.util.Dom.get('open'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                YAHOO.util.Dom.setStyle(openbtn, 'display', 'none');
                                            }else{
                                                var closedbtn = YAHOO.util.Dom.get('closed'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                YAHOO.util.Dom.setStyle(closedbtn, 'display', 'none');
                                                var openbtn = YAHOO.util.Dom.get('open'+cameras[i].childNodes[1].firstChild.nodeValue);
                                                YAHOO.util.Dom.setStyle(openbtn, 'display', '');
                                            }
                                        }
                                        var select = YAHOO.util.Selector.query('.formWFS', cameras[i].childNodes[1].firstChild.nodeValue, true);
                                        YAHOO.util.Dom.setStyle(select, 'display', 'none');
                                        var backBtnImgWF = YAHOO.util.Dom.get('backImgWF'+cameras[i].childNodes[1].firstChild.nodeValue);
                                        backBtnImgWF.setAttribute('src', './icon_load/back-button-up.png');
                                        var backBtnImgWFS = YAHOO.util.Dom.get('backImgWFS'+cameras[i].childNodes[1].firstChild.nodeValue);
                                        backBtnImgWFS.setAttribute('src', './icon_load/back-button-up.png');
                                        var validBtnImgWF = YAHOO.util.Dom.get('validImgWF'+cameras[i].childNodes[1].firstChild.nodeValue);
                                        validBtnImgWF.setAttribute('src', './icon_load/valid-button-up.png');
                                        var validBtnImgWFS = YAHOO.util.Dom.get('validImgWFS'+cameras[i].childNodes[1].firstChild.nodeValue);
                                        validBtnImgWFS.setAttribute('src', './icon_load/valid-button-up.png');
                                    }
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurRefresh", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                },
                              timeout: 180000,
                            }; ";

        //Callbck du verrou d'une caméra. Si il y a succés, on affiche les boutons de contrôle.
        $codeJS .= "var callbackGetCam =
                            {
                              success: function(o) {
                                    cameraName = o.responseXML.getElementsByTagName('cameraName')[0].firstChild.nodeValue;
                                    camera = o.responseXML.getElementsByTagName('cameraUuid')[0].firstChild.nodeValue;
                                    var success = o.responseXML.getElementsByTagName('success');
                                    if(success[0].firstChild.nodeValue == 'SUCCESS'){
                                       var cmddiv = YAHOO.util.Dom.get('cmd'+camera);
                                       YAHOO.util.Dom.setStyle(cmddiv, 'display', '');
                                       var lockbtn = YAHOO.util.Dom.get('open'+camera);
                                       YAHOO.util.Dom.setStyle(lockbtn, 'display', 'none');
                                    }else{
                                        alert(o.responseXML.getElementsByTagName('reason')[0].firstChild.nodeValue);
                                        var lockbtn = YAHOO.util.Selector.query('.open', camera, true);
                                        YAHOO.util.Dom.setStyle(lockbtn, 'display', 'none');
                                        var locked = YAHOO.util.Selector.query('.closed', camera, true);
                                        YAHOO.util.Dom.setStyle(locked, 'display', '');
                                        var FBN = YAHOO.util.Dom.get('feedBackN');
                                        YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                        var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                        FBtext.innerHTML = '".get_string("erreurGet", "podcast")."';
                                    }
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    var lockImg = YAHOO.util.Dom.get('lockImg'+camera);
                                    lockImg.setAttribute('src', './icon_load/locker-button-up.png');
                                },
                              failure: function(o) {
                                    var FBN = YAHOO.util.Dom.get('feedBackN');
                                    YAHOO.util.Dom.setStyle(FBN, 'display', '');
                                    var FBtext = YAHOO.util.Dom.get('feedBackNText');
                                    FBtext.innerHTML = '".get_string("erreurGet", "podcast")."';
                                    var barre = YAHOO.util.Dom.get('loadingBar');
                                    YAHOO.util.Dom.setStyle(barre, 'display', 'none');
                                    var lockImg = YAHOO.util.Dom.get('lockImg'+camera);
                                    lockImg.setAttribute('src', './icon_load/locker-button-up.png');
                                },
                              timeout: 15000,
                            }; ";

        //Code JS de la demande.
        $codeJS .= "function Record(elm, cam){
                            var cmddiv = YAHOO.util.Dom.get('cmd'+elm);
                            var recordbtnimg = YAHOO.util.Dom.get('recordImg'+elm);
                            recordbtnimg.setAttribute('src', './icon_load/record-button-down.png');
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/PcPDo.php?cmd=start&cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackRecord);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function getCam(elm, cam){
                            var lockImg = YAHOO.util.Dom.get('lockImg'+elm);
                            lockImg.setAttribute('src', './icon_load/locker-button-down.png');
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/getCam.php?cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackGetCam);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function Stop(elm, cam){
                            var stopbtimg = YAHOO.util.Dom.get('stopImg'+elm);
                            stopbtimg.setAttribute('src', './icon_load/stop-button-down.png');
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/listWorkflows.php?cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackStop);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function Pause(elm, cam){
                            var pausebtnImg = YAHOO.util.Dom.get('pauseImg'+elm);
                            pausebtnImg.setAttribute('src', './icon_load/pause-button-down.png');
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/PcPDo.php?cmd=pause&cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackPause);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function Play(elm, cam){
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/PcPDo.php?cmd=resume&cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackResume);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function Cancel(elm, cam){
                            var cancelbtnImg = YAHOO.util.Dom.get('cancelImg'+elm);
                            cancelbtnImg.setAttribute('src', './icon_load/cancel-button-down.png');
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/PcPDo.php?cmd=cancel&cam='+cam+'&uuid='+elm+'&instid=".$id."', callbackCancel);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";

        $codeJS .= "function RefreshCams(){
                            var connectionObject = YAHOO.util.Connect.asyncRequest ('Get', '".$CFG->wwwroot."/mod/podcast/refreshCams.php?cid=".$COURSE->id."&instid=".$id."', callbackRefresh);
                            var barre = YAHOO.util.Dom.get('loadingBar');
                            YAHOO.util.Dom.setStyle(barre, 'display', '');
                            HideFB();
                    }";


        $codeJS .= "function HideFB(){
                        var FBN = YAHOO.util.Dom.get('feedBackN');
                        var FBP = YAHOO.util.Dom.get('feedBackP');
                        YAHOO.util.Dom.setStyle(FBN, 'display', 'none');
                        YAHOO.util.Dom.setStyle(FBP, 'display', 'none');
                        var FBNtext = YAHOO.util.Dom.get('feedBackNText');
                        var FBPtext = YAHOO.util.Dom.get('feedBackPText');
                        FBNtext.innerHTML = '';
                        FBPtext.innerHTML = '';
                    }";

        $codeJS .= metaDataHandler('camera', $id);

        //On lance une connexion pour aovir l'état des caméras.
        $codeJS .= "RefreshCams();";
        //<|Script>
        $codeJS .= "</script>";
        echo $codeJS;
    }else{
        error("Permission denied");
    }
}

// Format de fichier multimedia accepésr par défault
function get_podcast_mimetypes() {
    return array ('avi','mov','movie','m3u','mp3','mp4','m4v','mpeg','mpe','mpg','m4a','qt','wmv','asf');
}

// Format de fichier multimedia acceptés par défaut, sous forme de string
function get_podcast_mimetypes_string() {
	 $string = "avi, mov, movie, m3u, mp3 , mp4, m4v, mpeg, mpe, mpg, m4a, qt, wmv, asf";
	 return $string;
}

// Récuperer l'extension d'un fichier
function get_extension($file) {
    if (eregi('\.([a-z0-9]+)$', $file, $match)) {
    	return strtolower($match[1]);
    } else {
        return 'xxx';
    }
}

// Récuperer la liste des formats de fichier configurés par l'utilisateur
function get_podcast_limit_mimetypes($default=true) {
   	
	global $CFG;

	$types = explode(",",$CFG->podcast_extensions);
	$new_ext = array();
	$good_ext = get_podcast_mimetypes();

	foreach($types as $type) {
	
		$type = trim($type);
		if (in_array($type,$good_ext))
			array_push($new_ext,$type);
	}

	if ($default && count($new_ext) == 0)
		$new_ext = $good_ext;
	
	return $new_ext;
}

// Sauvegarder le fichier XML
function podcast_save_file ($file, $content) {
 
    $status = true;

        $rss_file = fopen($file, "w");	
        if ($rss_file) {
            $status = fwrite ($rss_file, $content);
            fclose($rss_file);
        } else {
            $status = false;
        }
    return $status;
}
	
// Créer le fichier XML 2.0
function make_xml_podcast($podcast) { 
	
	global $CFG;
	
	$podcast_item = get_records("podcast_structure", "id_podcast", $podcast->id);
	
	$path = $CFG->dirroot."/mod/podcast/publication/".$podcast->course."/";

	if (!is_dir($path)) 
		mkdir($path);

	
	$file = $path."rss".$podcast->id.".xml";
	
	//On nettoie avant de construire le xml
	clean_podcast(&$podcast, &$podcast_item);
	
	$erreur = podcast_save_file($file,make_xml($podcast, $podcast_item, false));	
	
	if($CFG->podcast_fluxipod){
		$file = $path."rss".$podcast->id."-ipod.xml";
	
		$erreur = podcast_save_file($file,make_xml($podcast, $podcast_item, true));
	}
	
	return $erreur;
	
}
 
// Véfication du format d'un fichier
function check_podcast_extension($file) {
	
	if (in_array(get_extension($file),get_podcast_limit_mimetypes()))
		return true;	
	else
		return false;
		
}

// Effacer un complétement dossier
function effacer($path) {
    $O = dir($path);
    if(!is_object($O))
    return false;
    
    while($file = $O -> read()) {
        if($file != '.' && $file != '..') {
            if(is_file($path.'/'.$file))
            unlink($path.'/'.$file);
            else if(is_dir($path.'/'.$file))
            	effacer($path.'/'.$file);
            }
        }
    $O -> close();
    $O -> close();

    rmdir($path);
    return true;
}

//Effacer un item de la solution de podcast
function deleteItem($item, $podcast, $id){
global $CFG;
    if (! $itemObj = get_record($CFG->podcast_feed, "id", "$item")) {
        error(get_string('erreurDelete', 'podcast'));
    }else{
		//On update que les chaps concernés.
		$updateObj = new stdClass;
		$updateObj->id = $itemObj->id;
		$updateObj->alive = 0;
		if(update_record($CFG->podcast_feed, $updateObj)){
			echo "<center><font style='color:red;text-align:center;font-size:0.8em;font-weight:bold;'>";
			echo get_string('element', 'podcast')." \"".$itemObj->title."\" ".get_string('asDelete', 'podcast');
			echo "<br>";
			echo get_string('recupDeletedItem', 'podcast')."<br></font>";
			echo "<a  href='view.php?id=$id&tab=manage&recup=$itemObj->id'>".get_string('cliqueRecup', 'podcast')."</a><br><br>";
			echo "</center>";
		}else{
			error("impossible de supprimer $itemObj->title");
			return false;
		}
	}
}

//Récupérer un élément marqué pour la suppression de la solution de podcast.
function recupItem($item, $podcast, $id){
global $CFG;
    if (! $itemObj = get_record($CFG->podcast_feed, "id", "$item")) {
        error(get_string('noSuchItem', 'podcast'));
    }else{
		//On update que les chaps concernés.
		$updateObj = new stdClass;
		$updateObj->id = $itemObj->id;
		$updateObj->alive = 1;
		if(update_record($CFG->podcast_feed, $updateObj)){
			//On rend compte de la récupération du docment
			echo "<center><font style='color:green;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string("recupOK", "podcast")."</font></center>";
		}else{
			error("$itemObj->title is already gone..");
		}
	}
}

//Ajoute l'item au podcast courant
function ajouterItem($item, $podcast, $id){
	global $CFG;
    if (! $itemObj = get_record($CFG->podcast_feed, "id", "$item")) {
        error(get_string('noSuchItem', 'podcast'));
    }else{
		$insertObj = new stdClass;
		$insertObj->title = AddSlashes($itemObj->title);
		$insertObj->id_podcast = $podcast->id;
		$insertObj->lien = $itemObj->link;
		$insertObj->intro = AddSlashes($itemObj->desc);
		$insertObj->date_html = $itemObj->date;
		if(insert_record("podcast_structure", $insertObj)){
			//On rend compte de la l'ajout de l'item dans le podcast
			echo "<center><font style='color:green;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string("add_ok", "podcast")."</font></center>";
		}else{
			error("Insert Error");
		}
	}
	// XML 	
		if (make_xml_podcast($podcast))
			echo "<p style='color:green;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string('xml_ok','podcast')."</p>";
		else
			echo "<p style='color:red;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string('xml_error','podcast')."</p>";
}

//Enlve l'item du podcast courant
function enleverItem($item, $podcast, $id){

	if(!delete_records_select("podcast_structure", "id = ".$item)) {
		//error("Could not delete item podcast");
	} else {
		echo "<p style='color:green;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string('del_ok','podcast')."</p>";
	
		// XML 	
		if (make_xml_podcast($podcast))
			echo "<p style='color:green;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string('xml_ok','podcast')."</p>";
		else
			echo "<p style='color:red;text-align:center;font-size:0.8em;font-weight:bold;'>".get_string('xml_error','podcast')."</p>";
	} 
}
?>
